package com.aaa.config;

import com.aaa.dao.UserDao;
import com.aaa.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 创建UserDetailsService的接口的实现类
 * 这个实现类需要实现的唯一方法的作用就是 根据security 提供的用户名
 * 去数据库中去查询 密码 交给security
 *
 */
@Component
public class MyUserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserDao usersDao;

    /**
     * 通过用户名加载用户信息
     * @param username 用户名
     * @return 返回用户的用户信息
     * @throws UsernameNotFoundException 未发现该用户
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
         //根据username 去数据库查询用户数据
        User user = usersDao.findUserInfoByUsername(username);
        if(user==null) throw new UsernameNotFoundException("用户名不存在");

        List<GrantedAuthority> authorities = new ArrayList<>();

        //去数据库把用户的权限信息查询出来 往authorities这个里面放
        user.setAuthorities(authorities);
        return user;
    }
}
